<!--
 * @Author: 螺丝 d1bug@sina.com
 * @Date: 2023-04-05 16:21:47
 * @LastEditors: 螺丝 d1bug@sina.com
 * @LastEditTime: 2023-04-12 23:47:29
 * @FilePath: /mall4v/src/components/pic-upload/index.vue
 * @Description: 
 * 
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved. 
-->
<template>
  <div>
    <el-upload class="pic-uploader-component" :action="$http.adornUrl('/admin/file/upload/element')"
      :headers="{ Authorization: $cookie.get('Authorization') }" :show-file-list="false" :on-success="handleUploadSuccess"
      :before-upload="beforeAvatarUpload">
      <img v-if="value && getFileExName()" :src="resourcesUrl + value" class="pic">
      <video v-else-if="!getFileExName()" :src="resourcesUrl + value" class="pic"></video>
      <i v-else class="el-icon-plus pic-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
export default {
  data() {
    return {
      resourcesUrl: process.env.VUE_APP_RESOURCES_URL
    }
  },
  props: {
    value: {
      default: '',
      type: String
    }
  },
  methods: {
    getFileExName() {
      let name = this.value.split('.');
      if (name[1] == "mp4") {
        return false;
      }
      return true;
    },
    // 图片上传
    handleUploadSuccess(response, file, fileList) {
      this.$emit('input', file.response.data)
    },
    // 限制图片上传大小
    beforeAvatarUpload(file) {
      console.log(file.type);

      const isLt2M = file.size / 1024 / 1024 < 200
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type === "video/mp4"
      if (!isJPG) {
        this.$message.error('上传图片只能是jpeg/jpg/png/gif/mp4 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过200MB!')
      }
      return isLt2M && isJPG
    }
  }
}
</script>

<style lang="scss">
.pic-uploader-component .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  .pic-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .pic {
    width: 178px;
    height: 178px;
    display: block;
  }
}

.pic-uploader-component .el-upload:hover {
  border-color: #409EFF;
}
</style>
